﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using WeChatService.Models.efmodel;
using Webdiyer.WebControls.Mvc;

namespace WeChatService.Models.service
{
    public class MessageService : ServiceBase<Message>
    {
        public Message getByID(int id)
        {
            return we.Message.SingleOrDefault(t => t.ID == id);
        }

        public PagedList<Message> getPage(string serkey, int pi, int pz, string type)
        {
            if (String.IsNullOrEmpty(serkey))
            {
                if (String.IsNullOrEmpty(type))
                {
                    return we.Message.OrderByDescending(j => j.ID).ToPagedList(pi, pz);
                }
                else
                {
                    return we.Message.Where(j => j.Type == type).OrderByDescending(j => j.ID).ToPagedList(pi, pz);
                }

            }
            else
            {
                if (String.IsNullOrEmpty(type))
                {
                    return we.Message.Where(j => (j.Title.Contains(serkey) || j.Description.Contains(serkey)
                                                  || j.Text.Contains(serkey)))
                             .OrderByDescending(j => j.ID).ToPagedList(pi, pz);
                }
                else
                {
                    return we.Message.Where(j => j.Type == type && (j.Title.Contains(serkey) || j.Description.Contains(serkey)
                            || j.Text.Contains(serkey)))
                            .OrderByDescending(j => j.ID).ToPagedList(pi, pz);
                }
            }

            
        }

        public int Del(int ID)
        {
            return Del(getByID(ID));
        }

        public int Edit(Message msg)
        {
            Message m = getByID(msg.ID);
            m.Title = msg.Title;
            if (!String.IsNullOrEmpty(msg.ImgUrl))
            {
                m.ImgUrl = msg.ImgUrl;
            }
            m.Description = msg.Description;
            m.Text = msg.Text;
            m.MusicURL = msg.MusicURL;
            m.Url = msg.Url;
            m.CreateTime = DateTime.Now;
            return we.SaveChanges();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mids">mids是以；分割的消息ID 字符串</param>
        /// <returns></returns>
        public List<Message> getListByMids(String mids)
        {
            mids = mids.Trim(';');
            String[] mid ;
            if (mids.Contains(";"))
            {
                mid = mids.Split(';');
            }
            else
            {
                mid = new string[]{ mids };
            }
            List<Message> list = new List<Message>();
            foreach (var s in mid)
            {
                int id = int.Parse(s);
                Message message = getByID(id);
                list.Add(message);
            }
            return list;
        }

    }
}